"use client"

import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Progress } from "@/components/ui/progress"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Slider } from "@/components/ui/slider"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import {
  Calculator,
  DollarSign,
  TrendingUp,
  BarChart3,
  CheckCircle,
  Target,
  Zap,
  Download,
  Eye,
  RefreshCw,
  LineChart,
  Activity,
  Shield,
  Lightbulb,
} from "lucide-react"
import { useState } from "react"

interface FinancialCalculatorProps {
  onClose: () => void
}

export function FinancialCalculator({ onClose }: FinancialCalculatorProps) {
  const [activeTab, setActiveTab] = useState("setup")
  const [calculationType, setCalculationType] = useState("comprehensive") // comprehensive, valuation, funding, scenario
  const [financialData, setFinancialData] = useState({
    // 基础财务数据
    currentRevenue: "",
    monthlyGrowthRate: "",
    grossMargin: "",
    operatingExpenses: "",
    marketingCosts: "",
    salariesBenefits: "",
    rentUtilities: "",
    otherExpenses: "",

    // 现金流数据
    initialCash: "",
    monthlyBurnRate: "",
    customerAcquisitionCost: "",
    customerLifetimeValue: "",
    churnRate: "",

    // 融资相关
    fundingAmount: "",
    equityOffered: "",
    preMoneyValuation: "",
    investorType: "",
    useOfFunds: "",

    // 预测参数
    forecastPeriod: "36", // 预测期间（月）
    revenueGrowthScenario: [15], // 收入增长率
    costInflationRate: [3], // 成本通胀率
    marketPenetration: [5], // 市场渗透率

    // 高级设置
    includeSeasonality: false,
    includeTaxes: true,
    taxRate: "25",
    discountRate: "12",
    terminalGrowthRate: "3",

    // 情景分析
    optimisticGrowth: "",
    pessimisticGrowth: "",
    baselineGrowth: "",
  })

  const [isCalculating, setIsCalculating] = useState(false)
  const [calculationResult, setCalculationResult] = useState(null)
  const [calculationProgress, setCalculationProgress] = useState(0)

  const calculationTypes = [
    {
      id: "comprehensive",
      name: "综合财务分析",
      description: "全面的财务预测和分析",
      icon: Calculator,
    },
    {
      id: "valuation",
      name: "企业估值模型",
      description: "DCF、市场倍数等估值方法",
      icon: TrendingUp,
    },
    {
      id: "funding",
      name: "融资计算器",
      description: "股权稀释、融资轮次分析",
      icon: DollarSign,
    },
    {
      id: "scenario",
      name: "情景分析",
      description: "乐观/悲观/基准情景对比",
      icon: BarChart3,
    },
  ]

  const investorTypes = ["天使投资人", "VC风投", "PE私募", "战略投资者", "政府基金", "银行贷款", "众筹", "其他"]

  const handleInputChange = (field, value) => {
    setFinancialData((prev) => ({ ...prev, [field]: value }))
  }

  const runCalculation = async () => {
    setIsCalculating(true)
    setActiveTab("calculation")
    setCalculationProgress(0)

    // 模拟计算过程
    const steps = [
      { name: "处理基础数据", duration: 800 },
      { name: "计算现金流", duration: 1200 },
      { name: "财务预测建模", duration: 1500 },
      { name: "估值计算", duration: 1000 },
      { name: "风险分析", duration: 800 },
      { name: "情景分析", duration: 1000 },
      { name: "生成报告", duration: 700 },
    ]

    let currentProgress = 0
    for (let i = 0; i < steps.length; i++) {
      await new Promise((resolve) => setTimeout(resolve, steps[i].duration))
      currentProgress = ((i + 1) / steps.length) * 100
      setCalculationProgress(currentProgress)
    }

    // 生成模拟计算结果
    const mockResult = {
      summary: {
        currentValuation: "2,500万元",
        projectedValuation: "8,000万元",
        monthlyBurnRate: "45万元",
        runwayMonths: 18,
        breakEvenMonth: 24,
        roi3Year: "285%",
        irr: "42%",
        healthScore: 78,
      },

      cashFlowProjection: {
        monthly: Array.from({ length: 36 }, (_, i) => ({
          month: i + 1,
          revenue: Math.round(100 + i * 15 + Math.random() * 20),
          expenses: Math.round(80 + i * 8 + Math.random() * 15),
          netCashFlow: Math.round(20 + i * 7 + Math.random() * 10),
          cumulativeCash: Math.round(200 + i * 25 + Math.random() * 30),
        })),
        yearly: [
          { year: 1, revenue: 1200, expenses: 960, netIncome: 240, cashFlow: 280 },
          { year: 2, revenue: 2400, expenses: 1680, netIncome: 720, cashFlow: 800 },
          { year: 3, revenue: 4200, expenses: 2520, netIncome: 1680, cashFlow: 1800 },
        ],
      },

      profitabilityAnalysis: {
        grossMargin: {
          current: 65,
          projected: 72,
          industry: 68,
          trend: "improving",
        },
        operatingMargin: {
          current: -15,
          projected: 25,
          industry: 18,
          trend: "improving",
        },
        netMargin: {
          current: -20,
          projected: 18,
          industry: 12,
          trend: "improving",
        },
        ebitdaMargin: {
          current: -10,
          projected: 28,
          industry: 22,
          trend: "improving",
        },
      },

      keyMetrics: {
        customerMetrics: {
          cac: { current: 800, target: 600, industry: 750 },
          ltv: { current: 3000, target: 4500, industry: 3200 },
          ltvCacRatio: { current: 3.75, target: 7.5, industry: 4.3 },
          churnRate: { current: 8, target: 5, industry: 7 },
          paybackPeriod: { current: 18, target: 12, industry: 15 },
        },
        operationalMetrics: {
          burnRate: { current: 45, projected: 35, runway: 18 },
          growthRate: { current: 15, target: 25, sustainable: 20 },
          marketShare: { current: 2.5, target: 8, addressable: 15 },
        },
      },

      valuationAnalysis: {
        dcfValuation: {
          presentValue: "6,800万元",
          terminalValue: "4,200万元",
          totalValue: "8,000万元",
          sharePrice: "32元",
          assumptions: {
            discountRate: "12%",
            terminalGrowth: "3%",
            forecastPeriod: "5年",
          },
        },
        comparableValuation: {
          revenueMultiple: { value: "8.5x", industry: "6.2x", premium: "37%" },
          ebitdaMultiple: { value: "15.2x", industry: "12.8x", premium: "19%" },
          userMultiple: { value: "1,200元", industry: "950元", premium: "26%" },
        },
        fairValueRange: {
          low: "5,500万元",
          mid: "8,000万元",
          high: "11,200万元",
          confidence: "75%",
        },
      },

      fundingAnalysis: {
        currentRound: {
          amount: "1,000万元",
          valuation: "8,000万元",
          equityOffered: "12.5%",
          postMoneyValuation: "9,000万元",
          dilution: "11.1%",
        },
        useOfFunds: [
          { category: "产品研发", amount: 400, percentage: 40 },
          { category: "市场营销", amount: 300, percentage: 30 },
          { category: "团队扩张", amount: 200, percentage: 20 },
          { category: "运营资金", amount: 100, percentage: 10 },
        ],
        fundingHistory: [
          { round: "种子轮", amount: 200, valuation: 1500, date: "2023-01" },
          { round: "天使轮", amount: 500, valuation: 4000, date: "2023-08" },
          { round: "A轮", amount: 1000, valuation: 8000, date: "2024-06" },
        ],
        nextRoundProjection: {
          timing: "18个月后",
          estimatedAmount: "3,000万元",
          projectedValuation: "2.5亿元",
          milestones: ["月收入达到500万", "用户突破10万", "实现盈亏平衡"],
        },
      },

      scenarioAnalysis: {
        scenarios: [
          {
            name: "乐观情景",
            probability: 25,
            assumptions: {
              revenueGrowth: "30%",
              marketPenetration: "12%",
              churnRate: "3%",
            },
            outcomes: {
              year3Revenue: "6,800万元",
              year3Valuation: "15亿元",
              breakEven: "18个月",
              roi: "450%",
            },
          },
          {
            name: "基准情景",
            probability: 50,
            assumptions: {
              revenueGrowth: "20%",
              marketPenetration: "8%",
              churnRate: "5%",
            },
            outcomes: {
              year3Revenue: "4,200万元",
              year3Valuation: "8亿元",
              breakEven: "24个月",
              roi: "285%",
            },
          },
          {
            name: "悲观情景",
            probability: 25,
            assumptions: {
              revenueGrowth: "10%",
              marketPenetration: "4%",
              churnRate: "8%",
            },
            outcomes: {
              year3Revenue: "2,400万元",
              year3Valuation: "3.5亿元",
              breakEven: "36个月",
              roi: "120%",
            },
          },
        ],
        sensitivityAnalysis: {
          revenueGrowth: {
            "-20%": { valuation: "4,800万", roi: "180%" },
            "-10%": { valuation: "6,400万", roi: "230%" },
            "0%": { valuation: "8,000万", roi: "285%" },
            "+10%": { valuation: "9,600万", roi: "340%" },
            "+20%": { valuation: "11,200万", roi: "395%" },
          },
          customerAcquisition: {
            "-30%": { valuation: "10,400万", roi: "365%" },
            "-15%": { valuation: "9,200万", roi: "325%" },
            "0%": { valuation: "8,000万", roi: "285%" },
            "+15%": { valuation: "6,800万", roi: "245%" },
            "+30%": { valuation: "5,600万", roi: "205%" },
          },
        },
      },

      riskAssessment: {
        overallRisk: "中等",
        riskScore: 6.2,
        riskFactors: [
          {
            category: "市场风险",
            level: "中等",
            score: 6,
            description: "市场竞争加剧，客户获取成本上升",
            impact: "收入增长放缓，估值下降15-25%",
            mitigation: ["差异化产品策略", "提升客户粘性", "拓展新市场"],
          },
          {
            category: "运营风险",
            level: "低",
            score: 4,
            description: "团队经验丰富，运营体系相对完善",
            impact: "运营效率提升，成本控制良好",
            mitigation: ["持续优化流程", "加强团队培训", "建立风控体系"],
          },
          {
            category: "财务风险",
            level: "中等",
            score: 7,
            description: "现金流紧张，依赖外部融资",
            impact: "资金链断裂风险，影响业务发展",
            mitigation: ["多元化融资渠道", "提高现金流管理", "控制烧钱速度"],
          },
          {
            category: "技术风险",
            level: "低",
            score: 3,
            description: "技术团队稳定，产品技术门槛适中",
            impact: "技术风险可控，产品迭代正常",
            mitigation: ["技术储备建设", "核心技术保护", "人才梯队培养"],
          },
        ],
        riskMitigation: {
          immediate: ["建立现金流预警机制", "优化客户获取渠道", "加强成本控制"],
          shortTerm: ["多元化收入来源", "提升运营效率", "建立战略合作"],
          longTerm: ["构建竞争壁垒", "国际市场拓展", "生态系统建设"],
        },
      },

      recommendations: {
        financial: [
          "优化现金流管理，延长资金使用周期",
          "提高收入质量，降低客户流失率",
          "合理控制成本增长，提升盈利能力",
          "建立多元化融资渠道，降低资金风险",
        ],
        operational: [
          "加强数据驱动决策，提升运营效率",
          "优化产品功能，提升用户体验",
          "建立完善的客户成功体系",
          "加强团队建设，提升执行力",
        ],
        strategic: ["明确差异化竞争策略", "加快市场扩张步伐", "建立战略合作伙伴关系", "准备下一轮融资计划"],
      },

      benchmarks: {
        industryComparison: {
          revenueGrowth: { you: 20, industry: 15, percentile: 75 },
          grossMargin: { you: 65, industry: 58, percentile: 80 },
          burnRate: { you: 45, industry: 52, percentile: 60 },
          cac: { you: 800, industry: 950, percentile: 70 },
          ltv: { you: 3000, industry: 2800, percentile: 65 },
        },
        stageComparison: {
          valuation: { you: 8000, stage: 6500, percentile: 70 },
          teamSize: { you: 25, stage: 22, percentile: 65 },
          fundingRaised: { you: 1700, stage: 1200, percentile: 80 },
          monthsToBreakeven: { you: 24, stage: 28, percentile: 60 },
        },
      },
    }

    setCalculationResult(mockResult)
    setIsCalculating(false)
    setActiveTab("results")
  }

  const canCalculate = financialData.currentRevenue && financialData.monthlyGrowthRate && financialData.grossMargin

  return (
    <Dialog open={true} onOpenChange={onClose}>
      <DialogContent className="max-w-7xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-2">
            <Calculator className="w-5 h-5" />
            <span>AI财务计算器</span>
          </DialogTitle>
        </DialogHeader>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="setup">财务设置</TabsTrigger>
            <TabsTrigger value="calculation" disabled={!calculationResult && !isCalculating}>
              计算过程
            </TabsTrigger>
            <TabsTrigger value="results" disabled={!calculationResult}>
              财务报告
            </TabsTrigger>
            <TabsTrigger value="insights" disabled={!calculationResult}>
              深度分析
            </TabsTrigger>
          </TabsList>

          <TabsContent value="setup" className="space-y-6 mt-6">
            {/* 计算类型选择 */}
            <Card>
              <CardHeader>
                <CardTitle>选择分析类型</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {calculationTypes.map((type) => {
                    const Icon = type.icon
                    return (
                      <Card
                        key={type.id}
                        className={`cursor-pointer transition-all ${
                          calculationType === type.id ? "border-blue-500 bg-blue-50" : "hover:border-slate-300"
                        }`}
                        onClick={() => setCalculationType(type.id)}
                      >
                        <CardContent className="p-4 text-center">
                          <Icon
                            className={`w-8 h-8 mx-auto mb-2 ${
                              calculationType === type.id ? "text-blue-600" : "text-slate-400"
                            }`}
                          />
                          <h4 className="font-medium mb-1">{type.name}</h4>
                          <p className="text-xs text-slate-600">{type.description}</p>
                        </CardContent>
                      </Card>
                    )
                  })}
                </div>
              </CardContent>
            </Card>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 基础财务数据 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <DollarSign className="w-5 h-5" />
                    <span>基础财务数据</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">当前月收入 *</label>
                      <Input
                        placeholder="例如：100万元"
                        value={financialData.currentRevenue}
                        onChange={(e) => handleInputChange("currentRevenue", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">月增长率 *</label>
                      <Input
                        placeholder="例如：15%"
                        value={financialData.monthlyGrowthRate}
                        onChange={(e) => handleInputChange("monthlyGrowthRate", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">毛利率 *</label>
                      <Input
                        placeholder="例如：65%"
                        value={financialData.grossMargin}
                        onChange={(e) => handleInputChange("grossMargin", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">月运营费用</label>
                      <Input
                        placeholder="例如：80万元"
                        value={financialData.operatingExpenses}
                        onChange={(e) => handleInputChange("operatingExpenses", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">营销费用</label>
                      <Input
                        placeholder="例如：30万元"
                        value={financialData.marketingCosts}
                        onChange={(e) => handleInputChange("marketingCosts", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">人员成本</label>
                      <Input
                        placeholder="例如：40万元"
                        value={financialData.salariesBenefits}
                        onChange={(e) => handleInputChange("salariesBenefits", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">租金水电</label>
                      <Input
                        placeholder="例如：5万元"
                        value={financialData.rentUtilities}
                        onChange={(e) => handleInputChange("rentUtilities", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">其他费用</label>
                      <Input
                        placeholder="例如：5万元"
                        value={financialData.otherExpenses}
                        onChange={(e) => handleInputChange("otherExpenses", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 现金流与客户数据 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Activity className="w-5 h-5" />
                    <span>现金流与客户数据</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">当前现金余额</label>
                      <Input
                        placeholder="例如：500万元"
                        value={financialData.initialCash}
                        onChange={(e) => handleInputChange("initialCash", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">月烧钱速度</label>
                      <Input
                        placeholder="例如：45万元"
                        value={financialData.monthlyBurnRate}
                        onChange={(e) => handleInputChange("monthlyBurnRate", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">客户获取成本(CAC)</label>
                      <Input
                        placeholder="例如：800元"
                        value={financialData.customerAcquisitionCost}
                        onChange={(e) => handleInputChange("customerAcquisitionCost", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">客户生命周期价值(LTV)</label>
                      <Input
                        placeholder="例如：3000元"
                        value={financialData.customerLifetimeValue}
                        onChange={(e) => handleInputChange("customerLifetimeValue", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="text-sm font-medium text-slate-700">客户流失率</label>
                    <Input
                      placeholder="例如：8%"
                      value={financialData.churnRate}
                      onChange={(e) => handleInputChange("churnRate", e.target.value)}
                      className="mt-1"
                    />
                  </div>

                  {(calculationType === "funding" || calculationType === "comprehensive") && (
                    <>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="text-sm font-medium text-slate-700">融资金额</label>
                          <Input
                            placeholder="例如：1000万元"
                            value={financialData.fundingAmount}
                            onChange={(e) => handleInputChange("fundingAmount", e.target.value)}
                            className="mt-1"
                          />
                        </div>
                        <div>
                          <label className="text-sm font-medium text-slate-700">出让股权</label>
                          <Input
                            placeholder="例如：15%"
                            value={financialData.equityOffered}
                            onChange={(e) => handleInputChange("equityOffered", e.target.value)}
                            className="mt-1"
                          />
                        </div>
                      </div>

                      <div>
                        <label className="text-sm font-medium text-slate-700">投资者类型</label>
                        <Select
                          value={financialData.investorType}
                          onValueChange={(value) => handleInputChange("investorType", value)}
                        >
                          <SelectTrigger className="mt-1">
                            <SelectValue placeholder="选择投资者类型" />
                          </SelectTrigger>
                          <SelectContent>
                            {investorTypes.map((type) => (
                              <SelectItem key={type} value={type}>
                                {type}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            </div>

            {/* 高级设置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Target className="w-5 h-5" />
                  <span>预测参数设置</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div>
                    <Label className="text-base font-medium">预测期间</Label>
                    <Select
                      value={financialData.forecastPeriod}
                      onValueChange={(value) => handleInputChange("forecastPeriod", value)}
                    >
                      <SelectTrigger className="mt-2">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="12">12个月</SelectItem>
                        <SelectItem value="24">24个月</SelectItem>
                        <SelectItem value="36">36个月</SelectItem>
                        <SelectItem value="60">60个月</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label className="text-base font-medium">税率设置</Label>
                    <Input
                      placeholder="25%"
                      value={financialData.taxRate}
                      onChange={(e) => handleInputChange("taxRate", e.target.value)}
                      className="mt-2"
                    />
                  </div>

                  <div>
                    <Label className="text-base font-medium">折现率</Label>
                    <Input
                      placeholder="12%"
                      value={financialData.discountRate}
                      onChange={(e) => handleInputChange("discountRate", e.target.value)}
                      className="mt-2"
                    />
                  </div>
                </div>

                <div>
                  <Label className="text-base font-medium">收入增长率预期</Label>
                  <div className="mt-2">
                    <Slider
                      value={financialData.revenueGrowthScenario}
                      onValueChange={(value) => handleInputChange("revenueGrowthScenario", value)}
                      max={50}
                      min={0}
                      step={1}
                      className="w-full"
                    />
                    <div className="flex justify-between text-sm text-slate-600 mt-1">
                      <span>0%</span>
                      <span className="font-medium">{financialData.revenueGrowthScenario[0]}%</span>
                      <span>50%</span>
                    </div>
                  </div>
                </div>

                <div>
                  <Label className="text-base font-medium">成本通胀率</Label>
                  <div className="mt-2">
                    <Slider
                      value={financialData.costInflationRate}
                      onValueChange={(value) => handleInputChange("costInflationRate", value)}
                      max={15}
                      min={0}
                      step={0.5}
                      className="w-full"
                    />
                    <div className="flex justify-between text-sm text-slate-600 mt-1">
                      <span>0%</span>
                      <span className="font-medium">{financialData.costInflationRate[0]}%</span>
                      <span>15%</span>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                  <div className="flex items-center justify-between">
                    <Label className="text-sm">包含季节性因素</Label>
                    <Switch
                      checked={financialData.includeSeasonality}
                      onCheckedChange={(checked) => handleInputChange("includeSeasonality", checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <Label className="text-sm">包含税务计算</Label>
                    <Switch
                      checked={financialData.includeTaxes}
                      onCheckedChange={(checked) => handleInputChange("includeTaxes", checked)}
                    />
                  </div>
                </div>

                {calculationType === "scenario" && (
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-700">乐观增长率</label>
                      <Input
                        placeholder="30%"
                        value={financialData.optimisticGrowth}
                        onChange={(e) => handleInputChange("optimisticGrowth", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">基准增长率</label>
                      <Input
                        placeholder="20%"
                        value={financialData.baselineGrowth}
                        onChange={(e) => handleInputChange("baselineGrowth", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-700">悲观增长率</label>
                      <Input
                        placeholder="10%"
                        value={financialData.pessimisticGrowth}
                        onChange={(e) => handleInputChange("pessimisticGrowth", e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            <div className="flex justify-center">
              <Button onClick={runCalculation} disabled={!canCalculate} className="px-8">
                <Calculator className="w-4 h-4 mr-2" />
                开始财务分析
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="calculation" className="space-y-6 mt-6">
            {isCalculating ? (
              <div className="text-center py-12">
                <Calculator className="w-12 h-12 text-blue-600 mx-auto mb-4 animate-pulse" />
                <h3 className="text-lg font-semibold text-slate-900 mb-2">AI正在进行财务建模分析</h3>
                <p className="text-slate-600 mb-4">正在计算现金流预测、估值模型、风险评估...</p>
                <Progress value={calculationProgress} className="w-80 mx-auto mb-4" />
                <div className="space-y-2 text-sm text-slate-500">
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress > 14 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress > 14 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full animate-spin" />
                    )}
                    <span>处理基础数据</span>
                  </div>
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress > 31 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress > 31 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full" />
                    )}
                    <span>计算现金流</span>
                  </div>
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress > 52 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress > 52 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full" />
                    )}
                    <span>财务预测建模</span>
                  </div>
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress > 66 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress > 66 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full" />
                    )}
                    <span>估值计算</span>
                  </div>
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress > 78 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress > 78 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full" />
                    )}
                    <span>风险分析</span>
                  </div>
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress > 92 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress > 92 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full" />
                    )}
                    <span>情景分析</span>
                  </div>
                  <div
                    className={`flex items-center justify-center space-x-2 ${calculationProgress === 100 ? "text-green-600" : ""}`}
                  >
                    {calculationProgress === 100 ? (
                      <CheckCircle className="w-4 h-4" />
                    ) : (
                      <div className="w-4 h-4 border-2 border-slate-300 rounded-full" />
                    )}
                    <span>生成报告</span>
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-12">
                <CheckCircle className="w-12 h-12 text-green-600 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-slate-900 mb-2">财务分析完成！</h3>
                <p className="text-slate-600 mb-4">详细的财务报告和分析结果已生成</p>
                <Button onClick={() => setActiveTab("results")}>查看财务报告</Button>
              </div>
            )}
          </TabsContent>

          <TabsContent value="results" className="space-y-6 mt-6">
            {calculationResult && (
              <div className="space-y-6">
                {/* 操作按钮 */}
                <div className="flex justify-between items-center">
                  <h2 className="text-xl font-semibold text-slate-900">财务分析报告</h2>
                  <div className="flex space-x-2">
                    <Button variant="outline" size="sm">
                      <RefreshCw className="w-4 h-4 mr-2" />
                      重新计算
                    </Button>
                    <Button variant="outline" size="sm">
                      <Eye className="w-4 h-4 mr-2" />
                      预览报告
                    </Button>
                    <Button variant="outline" size="sm">
                      <Download className="w-4 h-4 mr-2" />
                      导出Excel
                    </Button>
                  </div>
                </div>

                {/* 财务概览 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <BarChart3 className="w-5 h-5 text-blue-600" />
                      <span>财务概览</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                      <div className="text-center p-4 bg-blue-50 rounded-lg">
                        <div className="text-2xl font-bold text-blue-600">
                          {calculationResult.summary.currentValuation}
                        </div>
                        <div className="text-sm text-slate-600">当前估值</div>
                      </div>
                      <div className="text-center p-4 bg-green-50 rounded-lg">
                        <div className="text-2xl font-bold text-green-600">
                          {calculationResult.summary.projectedValuation}
                        </div>
                        <div className="text-sm text-slate-600">预期估值</div>
                      </div>
                      <div className="text-center p-4 bg-orange-50 rounded-lg">
                        <div className="text-2xl font-bold text-orange-600">
                          {calculationResult.summary.monthlyBurnRate}
                        </div>
                        <div className="text-sm text-slate-600">月烧钱速度</div>
                      </div>
                      <div className="text-center p-4 bg-purple-50 rounded-lg">
                        <div className="text-2xl font-bold text-purple-600">
                          {calculationResult.summary.runwayMonths}个月
                        </div>
                        <div className="text-sm text-slate-600">资金跑道</div>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <div className="text-center p-3 border border-slate-200 rounded-lg">
                        <div className="text-lg font-semibold text-slate-900">
                          {calculationResult.summary.breakEvenMonth}个月
                        </div>
                        <div className="text-sm text-slate-600">盈亏平衡点</div>
                      </div>
                      <div className="text-center p-3 border border-slate-200 rounded-lg">
                        <div className="text-lg font-semibold text-slate-900">{calculationResult.summary.roi3Year}</div>
                        <div className="text-sm text-slate-600">3年ROI</div>
                      </div>
                      <div className="text-center p-3 border border-slate-200 rounded-lg">
                        <div className="text-lg font-semibold text-slate-900">{calculationResult.summary.irr}</div>
                        <div className="text-sm text-slate-600">内部收益率</div>
                      </div>
                      <div className="text-center p-3 border border-slate-200 rounded-lg">
                        <div className="flex items-center justify-center space-x-2">
                          <div className="text-lg font-semibold text-slate-900">
                            {calculationResult.summary.healthScore}
                          </div>
                          <div
                            className={`w-3 h-3 rounded-full ${
                              calculationResult.summary.healthScore >= 80
                                ? "bg-green-500"
                                : calculationResult.summary.healthScore >= 60
                                  ? "bg-yellow-500"
                                  : "bg-red-500"
                            }`}
                          />
                        </div>
                        <div className="text-sm text-slate-600">财务健康度</div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* 盈利能力分析 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <TrendingUp className="w-5 h-5 text-green-600" />
                      <span>盈利能力分析</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                      {Object.entries(calculationResult.profitabilityAnalysis).map(([key, data]) => (
                        <div key={key} className="p-4 border border-slate-200 rounded-lg">
                          <h4 className="font-medium text-slate-900 mb-3 capitalize">
                            {key === "grossMargin"
                              ? "毛利率"
                              : key === "operatingMargin"
                                ? "营业利润率"
                                : key === "netMargin"
                                  ? "净利率"
                                  : "EBITDA利润率"}
                          </h4>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-slate-600">当前:</span>
                              <span className={`font-medium ${data.current >= 0 ? "text-green-600" : "text-red-600"}`}>
                                {data.current}%
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">预期:</span>
                              <span className="font-medium text-blue-600">{data.projected}%</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">行业:</span>
                              <span className="font-medium text-slate-700">{data.industry}%</span>
                            </div>
                            <div className="flex items-center space-x-1">
                              <TrendingUp
                                className={`w-3 h-3 ${data.trend === "improving" ? "text-green-500" : "text-red-500"}`}
                              />
                              <span
                                className={`text-xs ${data.trend === "improving" ? "text-green-600" : "text-red-600"}`}
                              >
                                {data.trend === "improving" ? "改善中" : "下降中"}
                              </span>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>

                {/* 关键指标 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <Target className="w-5 h-5 text-purple-600" />
                      <span>关键业务指标</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Tabs defaultValue="customer" className="w-full">
                      <TabsList className="grid w-full grid-cols-2">
                        <TabsTrigger value="customer">客户指标</TabsTrigger>
                        <TabsTrigger value="operational">运营指标</TabsTrigger>
                      </TabsList>

                      <TabsContent value="customer" className="mt-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {Object.entries(calculationResult.keyMetrics.customerMetrics).map(([key, data]) => (
                            <div key={key} className="p-4 border border-slate-200 rounded-lg">
                              <h4 className="font-medium text-slate-900 mb-3">
                                {key === "cac"
                                  ? "客户获取成本"
                                  : key === "ltv"
                                    ? "客户生命周期价值"
                                    : key === "ltvCacRatio"
                                      ? "LTV/CAC比率"
                                      : key === "churnRate"
                                        ? "客户流失率"
                                        : "回本周期"}
                              </h4>
                              <div className="space-y-2 text-sm">
                                <div className="flex justify-between">
                                  <span className="text-slate-600">当前:</span>
                                  <span className="font-medium text-slate-900">
                                    {key === "churnRate" || key === "ltvCacRatio"
                                      ? `${data.current}${key === "churnRate" ? "%" : "x"}`
                                      : key === "paybackPeriod"
                                        ? `${data.current}个月`
                                        : `${data.current}元`}
                                  </span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-slate-600">目标:</span>
                                  <span className="font-medium text-blue-600">
                                    {key === "churnRate" || key === "ltvCacRatio"
                                      ? `${data.target}${key === "churnRate" ? "%" : "x"}`
                                      : key === "paybackPeriod"
                                        ? `${data.target}个月`
                                        : `${data.target}元`}
                                  </span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-slate-600">行业:</span>
                                  <span className="font-medium text-slate-700">
                                    {key === "churnRate" || key === "ltvCacRatio"
                                      ? `${data.industry}${key === "churnRate" ? "%" : "x"}`
                                      : key === "paybackPeriod"
                                        ? `${data.industry}个月`
                                        : `${data.industry}元`}
                                  </span>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </TabsContent>

                      <TabsContent value="operational" className="mt-4">
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div className="p-4 border border-slate-200 rounded-lg">
                            <h4 className="font-medium text-slate-900 mb-3">现金流状况</h4>
                            <div className="space-y-2 text-sm">
                              <div className="flex justify-between">
                                <span className="text-slate-600">当前烧钱:</span>
                                <span className="font-medium text-red-600">
                                  {calculationResult.keyMetrics.operationalMetrics.burnRate.current}万/月
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-slate-600">预期烧钱:</span>
                                <span className="font-medium text-orange-600">
                                  {calculationResult.keyMetrics.operationalMetrics.burnRate.projected}万/月
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-slate-600">资金跑道:</span>
                                <span className="font-medium text-slate-900">
                                  {calculationResult.keyMetrics.operationalMetrics.burnRate.runway}个月
                                </span>
                              </div>
                            </div>
                          </div>

                          <div className="p-4 border border-slate-200 rounded-lg">
                            <h4 className="font-medium text-slate-900 mb-3">增长指标</h4>
                            <div className="space-y-2 text-sm">
                              <div className="flex justify-between">
                                <span className="text-slate-600">当前增长:</span>
                                <span className="font-medium text-blue-600">
                                  {calculationResult.keyMetrics.operationalMetrics.growthRate.current}%
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-slate-600">目标增长:</span>
                                <span className="font-medium text-green-600">
                                  {calculationResult.keyMetrics.operationalMetrics.growthRate.target}%
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-slate-600">可持续增长:</span>
                                <span className="font-medium text-slate-700">
                                  {calculationResult.keyMetrics.operationalMetrics.growthRate.sustainable}%
                                </span>
                              </div>
                            </div>
                          </div>

                          <div className="p-4 border border-slate-200 rounded-lg">
                            <h4 className="font-medium text-slate-900 mb-3">市场地位</h4>
                            <div className="space-y-2 text-sm">
                              <div className="flex justify-between">
                                <span className="text-slate-600">当前份额:</span>
                                <span className="font-medium text-slate-900">
                                  {calculationResult.keyMetrics.operationalMetrics.marketShare.current}%
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-slate-600">目标份额:</span>
                                <span className="font-medium text-blue-600">
                                  {calculationResult.keyMetrics.operationalMetrics.marketShare.target}%
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-slate-600">可获得份额:</span>
                                <span className="font-medium text-green-600">
                                  {calculationResult.keyMetrics.operationalMetrics.marketShare.addressable}%
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </TabsContent>
                    </Tabs>
                  </CardContent>
                </Card>

                {/* 现金流预测图表 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <LineChart className="w-5 h-5 text-indigo-600" />
                      <span>现金流预测</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="mb-4">
                      <h4 className="font-medium text-slate-900 mb-2">年度财务预测</h4>
                      <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                          <thead>
                            <tr className="border-b">
                              <th className="text-left py-2">年份</th>
                              <th className="text-right py-2">收入(万元)</th>
                              <th className="text-right py-2">支出(万元)</th>
                              <th className="text-right py-2">净利润(万元)</th>
                              <th className="text-right py-2">现金流(万元)</th>
                            </tr>
                          </thead>
                          <tbody>
                            {calculationResult.cashFlowProjection.yearly.map((year) => (
                              <tr key={year.year} className="border-b">
                                <td className="py-2 font-medium">第{year.year}年</td>
                                <td className="text-right py-2 text-green-600">{year.revenue}</td>
                                <td className="text-right py-2 text-red-600">{year.expenses}</td>
                                <td
                                  className={`text-right py-2 font-medium ${year.netIncome >= 0 ? "text-green-600" : "text-red-600"}`}
                                >
                                  {year.netIncome}
                                </td>
                                <td className="text-right py-2 text-blue-600">{year.cashFlow}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>

                    {/* 月度现金流趋势 */}
                    <div>
                      <h4 className="font-medium text-slate-900 mb-2">月度现金流趋势（前12个月）</h4>
                      <div className="h-32 bg-slate-50 rounded-lg flex items-end justify-between p-4">
                        {calculationResult.cashFlowProjection.monthly.slice(0, 12).map((month, index) => (
                          <div key={index} className="flex flex-col items-center">
                            <div
                              className={`w-4 rounded-t ${month.netCashFlow >= 0 ? "bg-green-500" : "bg-red-500"}`}
                              style={{ height: `${Math.abs(month.netCashFlow) * 2}px` }}
                            />
                            <div className="text-xs text-slate-600 mt-1">{month.month}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
            )}
          </TabsContent>

          <TabsContent value="insights" className="space-y-6 mt-6">
            {calculationResult && (
              <div className="space-y-6">
                {/* 估值分析 */}
                {(calculationType === "valuation" || calculationType === "comprehensive") && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center space-x-2">
                        <TrendingUp className="w-5 h-5 text-blue-600" />
                        <span>企业估值分析</span>
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        <div>
                          <h4 className="font-medium text-slate-900 mb-4">DCF估值模型</h4>
                          <div className="space-y-3">
                            <div className="flex justify-between">
                              <span className="text-slate-600">现值总和:</span>
                              <span className="font-medium">
                                {calculationResult.valuationAnalysis.dcfValuation.presentValue}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">终值:</span>
                              <span className="font-medium">
                                {calculationResult.valuationAnalysis.dcfValuation.terminalValue}
                              </span>
                            </div>
                            <div className="flex justify-between border-t pt-2">
                              <span className="text-slate-900 font-medium">企业总价值:</span>
                              <span className="font-bold text-blue-600">
                                {calculationResult.valuationAnalysis.dcfValuation.totalValue}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">每股价值:</span>
                              <span className="font-medium">
                                {calculationResult.valuationAnalysis.dcfValuation.sharePrice}
                              </span>
                            </div>
                          </div>
                        </div>

                        <div>
                          <h4 className="font-medium text-slate-900 mb-4">可比公司估值</h4>
                          <div className="space-y-3">
                            {Object.entries(calculationResult.valuationAnalysis.comparableValuation).map(
                              ([key, data]) => (
                                <div key={key} className="flex justify-between items-center">
                                  <span className="text-slate-600">
                                    {key === "revenueMultiple"
                                      ? "收入倍数:"
                                      : key === "ebitdaMultiple"
                                        ? "EBITDA倍数:"
                                        : "用户价值:"}
                                  </span>
                                  <div className="text-right">
                                    <div className="font-medium">{data.value}</div>
                                    <div className="text-xs text-slate-500">行业: {data.industry}</div>
                                    <Badge
                                      variant={data.premium.includes("+") ? "default" : "secondary"}
                                      className="text-xs"
                                    >
                                      溢价 {data.premium}
                                    </Badge>
                                  </div>
                                </div>
                              ),
                            )}
                          </div>
                        </div>
                      </div>

                      <div className="mt-6 p-4 bg-blue-50 rounded-lg">
                        <h4 className="font-medium text-blue-900 mb-2">估值区间</h4>
                        <div className="grid grid-cols-3 gap-4 text-center">
                          <div>
                            <div className="text-sm text-slate-600">保守估值</div>
                            <div className="font-semibold text-slate-900">
                              {calculationResult.valuationAnalysis.fairValueRange.low}
                            </div>
                          </div>
                          <div>
                            <div className="text-sm text-slate-600">合理估值</div>
                            <div className="font-bold text-blue-600">
                              {calculationResult.valuationAnalysis.fairValueRange.mid}
                            </div>
                          </div>
                          <div>
                            <div className="text-sm text-slate-600">乐观估值</div>
                            <div className="font-semibold text-slate-900">
                              {calculationResult.valuationAnalysis.fairValueRange.high}
                            </div>
                          </div>
                        </div>
                        <div className="text-center mt-2">
                          <Badge variant="outline">
                            置信度: {calculationResult.valuationAnalysis.fairValueRange.confidence}
                          </Badge>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* 融资分析 */}
                {(calculationType === "funding" || calculationType === "comprehensive") && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center space-x-2">
                        <DollarSign className="w-5 h-5 text-green-600" />
                        <span>融资分析</span>
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        <div>
                          <h4 className="font-medium text-slate-900 mb-4">当前融资轮次</h4>
                          <div className="space-y-3">
                            <div className="flex justify-between">
                              <span className="text-slate-600">融资金额:</span>
                              <span className="font-medium text-green-600">
                                {calculationResult.fundingAnalysis.currentRound.amount}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">投前估值:</span>
                              <span className="font-medium">
                                {calculationResult.fundingAnalysis.currentRound.valuation}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">出让股权:</span>
                              <span className="font-medium text-orange-600">
                                {calculationResult.fundingAnalysis.currentRound.equityOffered}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">投后估值:</span>
                              <span className="font-medium text-blue-600">
                                {calculationResult.fundingAnalysis.currentRound.postMoneyValuation}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-slate-600">创始人稀释:</span>
                              <span className="font-medium text-red-600">
                                {calculationResult.fundingAnalysis.currentRound.dilution}
                              </span>
                            </div>
                          </div>
                        </div>

                        <div>
                          <h4 className="font-medium text-slate-900 mb-4">资金用途分配</h4>
                          <div className="space-y-3">
                            {calculationResult.fundingAnalysis.useOfFunds.map((item, index) => (
                              <div key={index} className="flex items-center justify-between">
                                <span className="text-slate-600">{item.category}:</span>
                                <div className="flex items-center space-x-2">
                                  <div className="w-20 h-2 bg-slate-200 rounded-full">
                                    <div
                                      className="h-2 bg-blue-500 rounded-full"
                                      style={{ width: `${item.percentage}%` }}
                                    />
                                  </div>
                                  <span className="font-medium text-sm">
                                    {item.amount}万 ({item.percentage}%)
                                  </span>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>

                      <div className="mt-6">
                        <h4 className="font-medium text-slate-900 mb-4">融资历史</h4>
                        <div className="overflow-x-auto">
                          <table className="w-full text-sm">
                            <thead>
                              <tr className="border-b">
                                <th className="text-left py-2">轮次</th>
                                <th className="text-right py-2">金额(万元)</th>
                                <th className="text-right py-2">估值(万元)</th>
                                <th className="text-right py-2">时间</th>
                              </tr>
                            </thead>
                            <tbody>
                              {calculationResult.fundingAnalysis.fundingHistory.map((round, index) => (
                                <tr key={index} className="border-b">
                                  <td className="py-2 font-medium">{round.round}</td>
                                  <td className="text-right py-2 text-green-600">{round.amount}</td>
                                  <td className="text-right py-2">{round.valuation}</td>
                                  <td className="text-right py-2 text-slate-600">{round.date}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </div>

                      <div className="mt-6 p-4 bg-green-50 rounded-lg">
                        <h4 className="font-medium text-green-900 mb-2">下轮融资预测</h4>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div>
                            <div className="text-sm text-slate-600">预计时间</div>
                            <div className="font-medium">
                              {calculationResult.fundingAnalysis.nextRoundProjection.timing}
                            </div>
                          </div>
                          <div>
                            <div className="text-sm text-slate-600">预计金额</div>
                            <div className="font-medium text-green-600">
                              {calculationResult.fundingAnalysis.nextRoundProjection.estimatedAmount}
                            </div>
                          </div>
                          <div>
                            <div className="text-sm text-slate-600">预计估值</div>
                            <div className="font-medium text-blue-600">
                              {calculationResult.fundingAnalysis.nextRoundProjection.projectedValuation}
                            </div>
                          </div>
                        </div>
                        <div className="mt-3">
                          <div className="text-sm text-slate-600 mb-1">关键里程碑:</div>
                          <div className="flex flex-wrap gap-2">
                            {calculationResult.fundingAnalysis.nextRoundProjection.milestones.map(
                              (milestone, index) => (
                                <Badge key={index} variant="outline" className="text-xs">
                                  {milestone}
                                </Badge>
                              ),
                            )}
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* 情景分析 */}
                {(calculationType === "scenario" || calculationType === "comprehensive") && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center space-x-2">
                        <BarChart3 className="w-5 h-5 text-purple-600" />
                        <span>情景分析</span>
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-6">
                        {calculationResult.scenarioAnalysis.scenarios.map((scenario, index) => (
                          <div
                            key={index}
                            className={`p-4 rounded-lg border ${
                              scenario.name === "乐观情景"
                                ? "border-green-200 bg-green-50"
                                : scenario.name === "悲观情景"
                                  ? "border-red-200 bg-red-50"
                                  : "border-blue-200 bg-blue-50"
                            }`}
                          >
                            <div className="flex items-center justify-between mb-3">
                              <h4 className="font-medium text-slate-900">{scenario.name}</h4>
                              <Badge variant="outline">概率: {scenario.probability}%</Badge>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              <div>
                                <h5 className="text-sm font-medium text-slate-700 mb-2">关键假设</h5>
                                <div className="space-y-1 text-sm">
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">收入增长:</span>
                                    <span className="font-medium">{scenario.assumptions.revenueGrowth}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">市场渗透:</span>
                                    <span className="font-medium">{scenario.assumptions.marketPenetration}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">流失率:</span>
                                    <span className="font-medium">{scenario.assumptions.churnRate}</span>
                                  </div>
                                </div>
                              </div>

                              <div>
                                <h5 className="text-sm font-medium text-slate-700 mb-2">预期结果</h5>
                                <div className="space-y-1 text-sm">
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">3年收入:</span>
                                    <span className="font-medium">{scenario.outcomes.year3Revenue}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">3年估值:</span>
                                    <span className="font-medium">{scenario.outcomes.year3Valuation}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">盈亏平衡:</span>
                                    <span className="font-medium">{scenario.outcomes.breakEven}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span className="text-slate-600">投资回报:</span>
                                    <span className="font-medium text-green-600">{scenario.outcomes.roi}</span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>

                      {/* 敏感性分析 */}
                      <div className="mt-6">
                        <h4 className="font-medium text-slate-900 mb-4">敏感性分析</h4>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          <div>
                            <h5 className="text-sm font-medium text-slate-700 mb-3">收入增长率影响</h5>
                            <div className="space-y-2">
                              {Object.entries(calculationResult.scenarioAnalysis.sensitivityAnalysis.revenueGrowth).map(
                                ([change, result]) => (
                                  <div key={change} className="flex justify-between items-center text-sm">
                                    <span className="text-slate-600">{change}:</span>
                                    <div className="text-right">
                                      <div className="font-medium">{result.valuation}</div>
                                      <div className="text-xs text-green-600">{result.roi}</div>
                                    </div>
                                  </div>
                                ),
                              )}
                            </div>
                          </div>

                          <div>
                            <h5 className="text-sm font-medium text-slate-700 mb-3">获客成本影响</h5>
                            <div className="space-y-2">
                              {Object.entries(
                                calculationResult.scenarioAnalysis.sensitivityAnalysis.customerAcquisition,
                              ).map(([change, result]) => (
                                <div key={change} className="flex justify-between items-center text-sm">
                                  <span className="text-slate-600">{change}:</span>
                                  <div className="text-right">
                                    <div className="font-medium">{result.valuation}</div>
                                    <div className="text-xs text-green-600">{result.roi}</div>
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* 风险评估 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <Shield className="w-5 h-5 text-red-600" />
                      <span>风险评估</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="mb-6">
                      <div className="flex items-center justify-between mb-4">
                        <h4 className="font-medium text-slate-900">整体风险评级</h4>
                        <div className="flex items-center space-x-2">
                          <Badge
                            variant={
                              calculationResult.riskAssessment.overallRisk === "低"
                                ? "default"
                                : calculationResult.riskAssessment.overallRisk === "中等"
                                  ? "secondary"
                                  : "destructive"
                            }
                          >
                            {calculationResult.riskAssessment.overallRisk}风险
                          </Badge>
                          <span className="text-sm text-slate-600">
                            评分: {calculationResult.riskAssessment.riskScore}/10
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-4">
                      {calculationResult.riskAssessment.riskFactors.map((risk, index) => (
                        <div key={index} className="p-4 border border-slate-200 rounded-lg">
                          <div className="flex items-center justify-between mb-2">
                            <h5 className="font-medium text-slate-900">{risk.category}</h5>
                            <div className="flex items-center space-x-2">
                              <Badge
                                variant={
                                  risk.level === "低" ? "default" : risk.level === "中等" ? "secondary" : "destructive"
                                }
                              >
                                {risk.level}
                              </Badge>
                              <span className="text-sm text-slate-600">评分: {risk.score}/10</span>
                            </div>
                          </div>
                          <p className="text-sm text-slate-700 mb-2">{risk.description}</p>
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                            <div>
                              <span className="text-red-600 font-medium">潜在影响: </span>
                              <span className="text-slate-700">{risk.impact}</span>
                            </div>
                            <div>
                              <span className="text-green-600 font-medium">缓解措施: </span>
                              <ul className="text-slate-700 mt-1">
                                {risk.mitigation.map((measure, i) => (
                                  <li key={i} className="text-xs">
                                    • {measure}
                                  </li>
                                ))}
                              </ul>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>

                {/* 建议与行动计划 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <Lightbulb className="w-5 h-5 text-yellow-600" />
                      <span>专业建议</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Tabs defaultValue="financial" className="w-full">
                      <TabsList className="grid w-full grid-cols-3">
                        <TabsTrigger value="financial">财务建议</TabsTrigger>
                        <TabsTrigger value="operational">运营建议</TabsTrigger>
                        <TabsTrigger value="strategic">战略建议</TabsTrigger>
                      </TabsList>

                      <TabsContent value="financial" className="mt-4">
                        <ul className="space-y-2">
                          {calculationResult.recommendations.financial.map((rec, index) => (
                            <li key={index} className="flex items-start space-x-2">
                              <DollarSign className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
                              <span className="text-sm text-slate-700">{rec}</span>
                            </li>
                          ))}
                        </ul>
                      </TabsContent>

                      <TabsContent value="operational" className="mt-4">
                        <ul className="space-y-2">
                          {calculationResult.recommendations.operational.map((rec, index) => (
                            <li key={index} className="flex items-start space-x-2">
                              <Target className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
                              <span className="text-sm text-slate-700">{rec}</span>
                            </li>
                          ))}
                        </ul>
                      </TabsContent>

                      <TabsContent value="strategic" className="mt-4">
                        <ul className="space-y-2">
                          {calculationResult.recommendations.strategic.map((rec, index) => (
                            <li key={index} className="flex items-start space-x-2">
                              <Zap className="w-4 h-4 text-purple-500 mt-0.5 flex-shrink-0" />
                              <span className="text-sm text-slate-700">{rec}</span>
                            </li>
                          ))}
                        </ul>
                      </TabsContent>
                    </Tabs>
                  </CardContent>
                </Card>

                {/* 行业对比 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <BarChart3 className="w-5 h-5 text-indigo-600" />
                      <span>行业对比分析</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div>
                        <h4 className="font-medium text-slate-900 mb-4">行业平均对比</h4>
                        <div className="space-y-3">
                          {Object.entries(calculationResult.benchmarks.industryComparison).map(([key, data]) => (
                            <div key={key} className="flex items-center justify-between">
                              <span className="text-slate-600 capitalize">
                                {key === "revenueGrowth"
                                  ? "收入增长"
                                  : key === "grossMargin"
                                    ? "毛利率"
                                    : key === "burnRate"
                                      ? "烧钱速度"
                                      : key === "cac"
                                        ? "获客成本"
                                        : "客户价值"}
                                :
                              </span>
                              <div className="text-right">
                                <div className="flex items-center space-x-2">
                                  <span className="font-medium">
                                    {data.you}
                                    {key === "revenueGrowth" || key === "grossMargin"
                                      ? "%"
                                      : key === "cac" || key === "ltv"
                                        ? "元"
                                        : "万"}
                                  </span>
                                  <span className="text-slate-400">vs</span>
                                  <span className="text-slate-600">
                                    {data.industry}
                                    {key === "revenueGrowth" || key === "grossMargin"
                                      ? "%"
                                      : key === "cac" || key === "ltv"
                                        ? "元"
                                        : "万"}
                                  </span>
                                </div>
                                <div className="text-xs text-slate-500">排名: {data.percentile}%</div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>

                      <div>
                        <h4 className="font-medium text-slate-900 mb-4">同阶段企业对比</h4>
                        <div className="space-y-3">
                          {Object.entries(calculationResult.benchmarks.stageComparison).map(([key, data]) => (
                            <div key={key} className="flex items-center justify-between">
                              <span className="text-slate-600 capitalize">
                                {key === "valuation"
                                  ? "企业估值"
                                  : key === "teamSize"
                                    ? "团队规模"
                                    : key === "fundingRaised"
                                      ? "融资总额"
                                      : "盈亏平衡"}
                                :
                              </span>
                              <div className="text-right">
                                <div className="flex items-center space-x-2">
                                  <span className="font-medium">
                                    {data.you}
                                    {key === "valuation" || key === "fundingRaised"
                                      ? "万"
                                      : key === "teamSize"
                                        ? "人"
                                        : "月"}
                                  </span>
                                  <span className="text-slate-400">vs</span>
                                  <span className="text-slate-600">
                                    {data.stage}
                                    {key === "valuation" || key === "fundingRaised"
                                      ? "万"
                                      : key === "teamSize"
                                        ? "人"
                                        : "月"}
                                  </span>
                                </div>
                                <div className="text-xs text-slate-500">排名: {data.percentile}%</div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
            )}
          </TabsContent>
        </Tabs>

        <div className="flex justify-end mt-6">
          <Button variant="outline" onClick={onClose}>
            关闭
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
